import { Injectable, NotFoundException } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { PrismaService } from 'src/prisma/prisma.service';
import { UserService } from '../user/user.service';
import { isEmpty } from "lodash"
import * as bcrypt from 'bcrypt';
import { TokenService } from './services/token.service';
@Injectable()
export class AuthService {
  constructor(
    private readonly prismaService: PrismaService,
    private readonly userService: UserService,
    private readonly tokenService: TokenService
  ) {

  }

  async login(
    username: string,
    password: string,
    ip: string,
    ua: string,
  ): Promise<any> {
    const user = await this.userService.findUserByUserName(username)
    if (isEmpty(user))
      throw new NotFoundException('用户不存在')
    console.log(user, "用户这里")

    // 目前用户没有加盐
    // const isPasswordValid = await bcrypt.compare(password, user.password);
    // if (user.password !== isPasswordValid)
    //   throw new NotFoundException('密码无效')

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (user.password !== password)
      throw new NotFoundException('密码无效')

    // const roleIds = await this.roleService.getRoleIdsByUser(user.id)

    // const roles = await this.roleService.getRoleValues(roleIds)

    // 包含access_token和refresh_token
    // const token = await this.tokenService.generateAccessToken(user.id, roles)

    // await this.redis.set(genAuthTokenKey(user.id), token.accessToken, 'EX', this.securityConfig.jwtExprire)

    // // 设置密码版本号 当密码修改时，版本号+1
    // await this.redis.set(genAuthPVKey(user.id), 1)

    // // 设置菜单权限
    // const permissions = await this.menuService.getPermissions(user.id)
    // await this.setPermissionsCache(user.id, permissions)

    // await this.loginLogService.create(user.id, ip, ua)
    const token = await this.tokenService.generateToken(user)

    return {
      message: '登录成功',
      data: {
        token,
        userInfo: {
          userId: user.id,
          userName: user.username,
          createdAt: user.createdAt,
          ip,
          ua
        },
      },
    };
  }

  // 用户注册
  async register({ username, ...data }: any): Promise<void> {

  }
  create(createAuthDto: CreateAuthDto) {
    return 'This action adds a new auth';
  }

  findAll() {
    return `This action returns all auth`;
  }

  findOne(id: number) {
    return `This action returns a #${id} auth`;
  }

  update(id: number, updateAuthDto: UpdateAuthDto) {
    return `This action updates a #${id} auth`;
  }

  remove(id: number) {
    return `This action removes a #${id} auth`;
  }
  async validateUser(credential: string, password: string): Promise<any> {
    const user = await this.userService.findUserByUserName(credential)

    if (isEmpty(user))
      throw new NotFoundException(`用户不存在`);

    const isPasswordValid = await bcrypt.compare(password, user.password);
    if (user.password !== isPasswordValid)
      throw new NotFoundException(`密码不正确`);

    if (user) {
      const { password, ...result } = user
      return result
    }

    return null
  }


  // 退出登录
  async clearLoginStatus(user: IAuthUser, accessToken: string): Promise<any> {
    console.log('退出登录')
  }

}
